package com.lzh.shijicloudstack.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.shijicloudstack.mapper.IngredientCategoryMapper;
import com.lzh.shijicloudstack.model.entity.IngredientCategory;
import com.lzh.shijicloudstack.model.vo.category.CategoryVO;
import com.lzh.shijicloudstack.service.IngredientCategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luzhiheng
 * @date 2025-02-08
 */
@Service
public class IngredientCategoryServiceImpl extends ServiceImpl<IngredientCategoryMapper, IngredientCategory> implements IngredientCategoryService {

    @Override
    public List<CategoryVO> findList() {
        List<IngredientCategory> ingredientCategoryList = baseMapper.selectList(null);

        List<CategoryVO> dataList = ingredientCategoryList.stream()
                .map(e -> new CategoryVO()
                        .setId(e.getId())
                        .setLabel(e.getName())
                        .setValue(e.getCategoryId())
                        .setParentId(e.getParentId())
                        .setRemark(e.getRemark())
                        .setChildren(new ArrayList<>())
                        .setCreateName(e.getCreateName())
                        .setCreateTime(e.getCreateTime())
                        .setUpdateName(e.getUpdateName())
                        .setUpdateTime(e.getUpdateTime()))
                .collect(Collectors.toList());

        // 获取父级分类
        List<CategoryVO> parentList = dataList.stream().filter(e -> e.getParentId() == -1).collect(Collectors.toList());
        // 获取父级分类
        List<CategoryVO> childrenList = dataList.stream().filter(e -> e.getParentId() != -1).collect(Collectors.toList());
        // 递归
        this.recursionCategory(parentList, childrenList);
        return parentList;
    }

    private void recursionCategory(List<CategoryVO> parentList, List<CategoryVO> childrenList) {
        if (CollectionUtil.isEmpty(parentList) || CollectionUtil.isEmpty(childrenList)) {
            return;
        }

        Map<Long, List<CategoryVO>> idMap = childrenList.stream().collect(Collectors.groupingBy(CategoryVO::getParentId));

        for (CategoryVO parentVO : parentList) {
            Long parentId = parentVO.getId();
            List<CategoryVO> subList = parentVO.getChildren();
            List<CategoryVO> list = idMap.get(parentId);
            if (CollectionUtil.isNotEmpty(list)) {
                if (subList == null) {
                    subList = new ArrayList<>();
                }
                subList.addAll(list);
                parentVO.setChildren(subList);
                this.recursionCategory(subList, childrenList);
            }
        }
    }
}
